package com.mycjj.android.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.R;
import com.mycjj.android.bean.BaseBean;
import com.mycjj.android.bean.MemberBean;
import com.mycjj.android.bean.MemberBean.Member;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.util.Constants;
import com.mycjj.android.util.ImageUtil;
import com.mycjj.android.util.Preferences;

public class UserInfoActivity extends BaseActivity implements android.view.View.OnClickListener{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		initHeader();
		init();
	}

	private ImageView mHeaderLeftImageview;
	private Button mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	private void initHeader() {
		mHeaderLeftImageview = (ImageView) findViewById(R.id.header_left_button);
		mHeaderLeftImageview.setImageResource(R.drawable.back);
		mHeaderRightButton = (Button) findViewById(R.id.header_right_button);
		mHeaderRightButton.setVisibility(View.GONE);
		mHeaderTitleTextView = (TextView) findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("个人资料");
		mHeaderLeftImageview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				UserInfoActivity.this.finish();
			}
		});
	}

	private ImageView iv_header_pic;
	private EditText et_nickename;
	private Button mBtn_submit, mBtn_man, mBtn_woman;
	private View mCameraView;
	private Button mFromPhotoButton;
	private Button mFromCameraButton;
	private Button mCancelButton;

	private void init() {

		iv_header_pic = (ImageView) findViewById(R.id.iv_header_pic);
		et_nickename = (EditText) findViewById(R.id.et_nickename);
		mBtn_man = (Button) findViewById(R.id.btn_sex_man);
		mBtn_woman = (Button) findViewById(R.id.btn_sex_woman);
		mBtn_man.setOnClickListener(sexChangeListener);
		mBtn_woman.setOnClickListener(sexChangeListener);

		mBtn_submit = (Button) findViewById(R.id.btn_submit);
		mBtn_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				submit();
			}
		});
		iv_header_pic.setOnClickListener(picOnClickListener);
		mCameraView = findViewById(R.id.camera_linearlayout);
		mFromPhotoButton = (Button) findViewById(R.id.from_photo_button);
		mFromCameraButton = (Button) findViewById(R.id.from_camera_button);
		mCancelButton = (Button) findViewById(R.id.cancel_button);
		mFromPhotoButton.setOnClickListener(photoBtnOnClickListener);
		mFromCameraButton.setOnClickListener(photoBtnOnClickListener);
		mCancelButton.setOnClickListener(this);

		MemberBean bean = dataManager.getLoginMemberBean().getData();
		Member member = bean.getMember_arr();
		if (member != null) {
			avatar = member.getMember_avatar();
			imageLoader.displayImage(avatar, iv_header_pic);
			et_nickename.setText(member.getMember_truename());
			Log.e("mark", "sex:" + member.getMember_sex());
			if ("1".equals(member.getMember_sex())) {
				mBtn_man.setBackgroundResource(R.drawable.iv_sex_sel);
				mBtn_woman.setBackgroundResource(R.drawable.iv_sex_unsel);
			} else {
				mBtn_man.setBackgroundResource(R.drawable.iv_sex_unsel);
				mBtn_woman.setBackgroundResource(R.drawable.iv_sex_sel);
			}
		}
	}
	
	private String avatar;
	
	private OnClickListener photoBtnOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			mCameraView.setVisibility(View.GONE);
			switch (v.getId()) {
			case R.id.from_photo_button:
				selectPhoto();
				break;
			case R.id.from_camera_button:
				takePhoto();
				break;
			}
		}
	};
	
	
	
	private void takePhoto() {// 拍照
		// 调用系统自带的照相意图
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 将拍照的图片保存到sd卡中
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(Constants.DATA_DIR + "xxx.jpg")));
		startActivityForResult(cameraIntent, PHOTO_TAKE_DATA);// 调用系统相机操作
	}

	private void selectPhoto() {
		Intent photoIntent = new Intent(Intent.ACTION_GET_CONTENT);
		photoIntent.addCategory(Intent.CATEGORY_OPENABLE);
		photoIntent.setType("image/*");
		photoIntent.putExtra("return-data", true);
		startActivityForResult(photoIntent, PHOTO_PICKED_WITH_DATA);
	}

	private OnClickListener picOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mCameraView.getVisibility() == View.VISIBLE) {
				mCameraView.setVisibility(View.GONE);
			} else {
				mCameraView.setVisibility(View.VISIBLE);
			}
		}
	};

	private void submit() {
		String nickName = et_nickename.getText().toString().trim();
		if (TextUtils.isEmpty(nickName)) {
			Toast.makeText(UserInfoActivity.this, "昵称不能为空!", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		
		if(TextUtils.isEmpty(avatar)){
			if(f == null || !f.exists()){
				Toast.makeText(UserInfoActivity.this, "头像不能为空!", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		request = new ProjectHttpRequestImpl(UserInfoActivity.this, true);
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		params.put("token",
				Preferences.getSharedPreferences(this, "user_token", ""));
		params.put("member_truename", nickName);
		params.put("member_sex", String.valueOf(sex));
		try {
			if(f != null && f.exists()){
				params.put("member_avatar", f);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		request.requestUserEditMemberWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						@SuppressWarnings("all")
						BaseBean<Map> baseBean = (BaseBean<Map>)dataManager.getBaseBean();
						if(baseBean != null){
							if(baseBean.getCode() == 200){
								Map<?,?> map = baseBean.getData();
								String member_truename = map.get("member_truename").toString();
								String member_sex = map.get("member_sex").toString();
								String member_avatar = avatar;
								if(map.containsKey("member_avatar")){
									member_avatar = map.get("member_avatar").toString();
								}
								MemberBean bean = dataManager.getLoginMemberBean().getData();
								Member member = bean.getMember_arr();
								if (member != null) {
									member.setMember_avatar(member_avatar);
									member.setMember_truename(member_truename);
									member.setMember_sex(member_sex);
								}
								Log.e("mark", "member_truename:"+member_truename+";member_sex:"+member_sex+";member_avatar:"+member_avatar);
								Toast.makeText(UserInfoActivity.this, "修改成功！", Toast.LENGTH_SHORT).show();
							}else{
								Toast.makeText(UserInfoActivity.this, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
							}
						}else{
							Toast.makeText(UserInfoActivity.this, "BaseBean is null!", Toast.LENGTH_SHORT).show();
						}
					}
				});
	}

	private int sex = 1;
	private OnClickListener sexChangeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			v.setBackgroundResource(R.drawable.iv_sex_sel);
			switch (v.getId()) {
			case R.id.btn_sex_man:
				sex = 1;
				mBtn_woman.setBackgroundResource(R.drawable.iv_sex_unsel);
				break;
			case R.id.btn_sex_woman:
				sex = 2;
				mBtn_man.setBackgroundResource(R.drawable.iv_sex_unsel);
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.cancel_button:
			mCameraView.setVisibility(View.GONE);
			break;
		}
	}
	
	public static File f = null;
	File file = null;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("mark","requestCode:"+requestCode+";resultCode:"+resultCode+";");
		if (resultCode != RESULT_OK) {
			Log.e("mark","onActivityResult error....");
			return;
		}
		if(data != null){
			int type = data.getIntExtra("type", -1);//type
			if(type == 0){
				requestCode = 0;
			}
			Intent intent = null;
			switch(requestCode){
			case PHOTO_TAKE_DATA:
				file = new File(Constants.DATA_DIR + "qiqiu.jpg");
				if (file != null && file.exists()) {
					f = ImageUtil.getFileByFile(file, 480, 800);
					Log.e("mark","f path:" + f.getPath());
					intent = new Intent(this, CropperImageActivity.class);
					intent.putExtra("path", f.getPath());
					startActivityForResult(intent, PHOTO_CROP_DATA);
				}
				break;
			case PHOTO_PICKED_WITH_DATA: // 调用媒体库
				Uri uri = data.getData();
				ContentResolver contentResolver = this.getContentResolver();
				file = ImageUtil.getFileByUri(uri, contentResolver);
				if(file!=null && file.exists()){
					Log.e("mark","file:"+file.getPath());
					f = ImageUtil.getFileByFile(file, 480, 800);
					if(f != null){
						Log.e("mark","f exist:"+f.exists());
						Log.e("mark","f path:" + f.getPath());
					}
				}
				if (f != null) { // 调用剪切程序
					intent = new Intent(this, CropperImageActivity.class);
					intent.putExtra("path", f.getPath());
					startActivityForResult(intent, PHOTO_CROP_DATA);
				}
				break;
			case PHOTO_CROP_DATA: // 调用图片剪切程序返回数据
				String path = data.getStringExtra("data");
				File dataFile = new File(path);
				if (!dataFile.exists()) {
					Log.e("mark","path:"+path+" is not exist!!!");
					return;
				}
				iv_header_pic.setImageBitmap(BitmapFactory.decodeFile(path));
				return;
			}
		}
		
	}

}
